# -*- coding: utf-8 -*-

from tornado.escape import to_unicode
from wtforms import Form, StringField, validators, IntegerField
from wtforms_alchemy import ModelForm, QuerySelectField
from wtforms import widgets

from bopress.model import Users, UserRole
from bopress.orm import SessionFactory
from bopress.user import get_all_roles

__author__ = 'yezang'


class FormData(object):
    def __init__(self, handler):
        self._wrapped = handler.request.arguments

    def __iter__(self):
        return iter(self._wrapped)

    def __len__(self):
        return len(self._wrapped)

    def __contains__(self, name):
        return name in self._wrapped

    def getlist(self, name):
        try:
            return [to_unicode(v) for v in self._wrapped[name]]
        except KeyError:
            return []


class UserRegistryFrom(Form):
    user_email = StringField("Email", validators=[validators.input_required("必须填写"),
                                                  validators.email("邮箱格式错误")])
    user_pass = StringField("UserPass", validators=[validators.input_required("必须填写"),
                                                    validators.length(min=8, message="至少8个字母数字或下划线")])
    user_re_pass = StringField("UserPass2", validators=[validators.input_required("必须填写"),
                                                        validators.equal_to('user_pass', "密码不一致")])


class UserForm(Form):
    user_login = StringField("UserLogin", validators=[validators.input_required("必须填写")])
    user_nicename = StringField("UserNiceName")
    user_email = StringField("UserEmail", validators=[validators.input_required("必须填写"),
                                                      validators.email("邮箱格式错误")])
    user_mobile_phone = StringField("UserMobilePhone")
    display_name = StringField("DisplayName")
    user_status = IntegerField("UserStatus")


class UserRoleModelForm(ModelForm):
    class Meta:
        model = UserRole


def user_roles():
    items = list()
    roles = get_all_roles()
    for r in roles:
        items.append((r, roles[r][0]))
    return items


class UserModelForm(ModelForm):
    class Meta:
        model = Users
        exclude = ['user_registered', 'user_url', 'user_activation_key', 'user_pass']
        field_args = {'user_email': {'validators': [validators.input_required("必须填写"),
                                                    validators.email("邮箱格式错误")]},
                      'user_login': {'validators': [validators.input_required("必须填写")]}}

    roles = QuerySelectField('角色', query_factory=user_roles,
                             get_pk=lambda o: o[0], get_label=lambda o: o[1], validators=[validators.optional()])

    @staticmethod
    def get_session():
        return SessionFactory.session()


class UserProfileModelForm(ModelForm):
    class Meta:
        model = Users
        exclude = ['user_registered', 'user_url', 'user_activation_key', 'user_status', 'user_pass']
        field_args = {'user_email': {'validators': [validators.input_required("必须填写"),
                                                    validators.email("邮箱格式错误")]}}
    description = StringField("介绍", widget=widgets.TextArea())
    gravatar = StringField("头像")
    new_pass = StringField("设置新密码(不修改密码则不需要填写)", widget=widgets.PasswordInput(),
                           validators=[validators.length(min=8, message="至少8个字符"),
                                       validators.optional()])
    user_id = StringField("user_id", widget=widgets.HiddenInput())
    user_login = StringField("用户名")


class UserLoginFrom(Form):
    user_email = StringField("Email", validators=[validators.input_required("必须填写")])
    user_pass = StringField("UserPass", validators=[validators.input_required("必须填写")])


class TermTaxonomyForm(Form):
    name = StringField("name", validators=[validators.input_required("必须填写")])
    slug = StringField("slug", validators=[validators.input_required("必须填写")])
    description = StringField("description")
    position = IntegerField("position", validators=[validators.input_required("必须填写")])
    term_taxonomy_id = StringField("term_taxonomy_id")
    parent_id = StringField("parent_id")
